package com.hukun.ssm1110.entity;

import lombok.Data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Data
public class User {

    private int id;
    private String username;
    private String password;
    //添加一个属性为了方便我们 修改密码要用的一个新密码属性
    private String newPassword;
    //生日
    private Date birthday;
    //年龄
    private Integer age;

    private Integer permission;

    private String dateStr;

    //     重载getAge方法
    public Integer getAge() {
        int age = getUserAge(this.birthday);
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void setDateStr(String dateStr) {
        try {
            this.birthday = paresDate(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    private Date paresDate(String dateStr) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
        return sf.parse(dateStr);
    }

    private int getUserAge(Date birthDay) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDayAge = null;
        try {
            birthDayAge = sdf.parse(sdf.format(birthDay));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDayAge)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "日期填写错误！！");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDayAge);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;//当前日期在生日之前，年龄减一
                }
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }
}
